<template>
  <a-modal
    :title="title"
    style="top: 20px;"
    :width="800"
    v-model="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="cancel"
  >
    <template slot="footer">
      <div class="footerBox">
        <a-button class="button" @click="handleSubmit" type="primary">
          提交
        </a-button>
        <GenerateProtocol :form="formData" :disabled="serviceAgreement" >
          <a-button class="button" :disabled="serviceAgreement" @click="handleServiceAgreement" type="primary">
            生成服务协议
          </a-button>
        </GenerateProtocol>
        <GenerateServiceDeclaration :disabled="serviceStatement" >
          <a-button class="button" :disabled="serviceStatement" @click="handleServiceStatement" type="primary">
            生成服务声明
          </a-button>
        </GenerateServiceDeclaration>
        <a-button :disabled="clickOrder" class="button" @click="orderCompletion" type="primary">
          订单完成
        </a-button>
        <a-button @click="delByIds" class="button" type="primary">
          删除订单
        </a-button>
      </div>
    </template>
    <div class="headCard">
      <div class="headCardText">
        <span>经销商名称：</span>
        <span>{{ orderIdObj.dealerName }}</span>
      </div>
      <div class="headCardText">
        <span>机构代码：</span>
        <span>{{ orderIdObj.organCode }}</span>
      </div>
    </div>
    <a-form :form="form">
      <a-row>
        <a-col :md="24" >
          <div class="title">
            <div class="titleRece"></div>
            <span class="titleText">基本信息</span>
          </div>
        </a-col>
        <a-col :md="12" >
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="订单号">
            <a-input placeholder="订单号" :disabled="true" v-decorator="['orderId']"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" >
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="服务合同号">
            <a-input placeholder="服务合同号" :disabled="true" v-decorator="['serviceContractNo']"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" >
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="下单日期">
            <a-date-picker :disabled="true" valueFormat="YYYY-MM-DD" v-decorator="['orderTime']" style="width: 100%" placeholder="下单日期"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" >
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="业务员姓名">
            <a-input placeholder="业务员姓名" maxLength="18" v-decorator="['saleName', { initialValue: '', rules: [{ required: true, message: '业务员姓名不能为空' }, {pattern: /^[\u4e00-\u9fa5]{2,18}$/, message: '请输入正确的业务员姓名'}] }]"/>
          </a-form-item>
        </a-col>
        <a-col :md="24" >
          <div class="title">
            <div class="titleRece"></div>
            <span class="titleText">车辆信息</span>
          </div>
        </a-col>
        <a-col :md="12" >
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="车辆组别">
            <a-select placeholder="车辆组别" v-decorator="['carTypeName', { rules: [{ required: true, message: '车辆组别不能为空' }] }]">
              <a-select-option :value="'燃油'">燃油</a-select-option>
              <a-select-option :value="'混动'">混动</a-select-option>
              <a-select-option :value="'纯电'">纯电</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="12" >
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="">
            <a-radio-group v-decorator="['carType', { rules: [{ required: true, message: '类型不能为空' }] }]">
              <a-radio value="新车">
                新车
              </a-radio>
              <a-radio value="旧车">
                旧车
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :md="12" >
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="车辆品牌">
            <a-select placeholder="车辆品牌" @change="handlerCarBrand" v-decorator="['carBrand', { rules: [{ required: true, message: '车辆品牌不能为空' }] }]">
              <a-select-option v-for="(e, index) in brandClassList" :key="index" :value="e.carBrand">{{ e.carBrand }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="12" >
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="品牌型号">
            <a-input placeholder="品牌型号" maxLength="32" v-decorator="['brandModel', { rules: [{ required: true, message: '品牌型号不能为空' }, { pattern: /^[\s\S]{1,32}$/, message: '请输入正确的品牌型号'}] }]"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" >
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="车主姓名">
            <a-input placeholder="车主姓名" maxLength="18" v-decorator="['carName', { rules: [{ required: true, message: '车主姓名不能为空' }, {pattern: /^[\u4e00-\u9fa5]{2,18}$/, message: '请输入正确的车主姓名'}] }]"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" >
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="身份证号">
            <a-input placeholder="身份证号" maxLength="18" v-decorator="['idCard', { rules: [{ required: true, message: '身份证号不能为空' }, {pattern: /^[0-9(x|X)]{18}$/, message: '请输入正确的身份证号'}] }]"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" >
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="手机号">
            <a-input placeholder="手机号" maxLength="11" v-decorator="['iphone', { rules: [{ required: true, message: '手机号不能为空' }, {pattern: /^1\d{10}$/, message: '请输入正确的手机号'}] }]"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" >
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="服务权益人姓名">
            <a-input placeholder="服务权益人姓名" v-decorator="['serviceStakeholders', { rules: [{ required: true, message: '服务权益人姓名不能为空' }, {pattern: /^[\u4e00-\u9fa5]{2,18}$/, message: '请输入正确的服务权益人姓名'}] }]"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" >
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="车牌号/发动机号：">
            <a-input placeholder="车牌号" maxLength="25" v-decorator="['carNumber', { rules: [{ required: true, message: '车牌号/发动机号不能为空' }, , { pattern: /^[\da-zA-Z]{1,25}$/, message: '请输入正确的车牌号/发动机号'}] }]"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" >
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="车架号">
            <a-input placeholder="车架号" maxLength="25" v-decorator="['vinNo', { rules: [{ required: true, message: '车架号不能为空' }, { pattern: /^[\da-zA-Z]{1,25}$/, message: '请输入正确的车架号'}] }]"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" >
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="车险承保公司">
            <a-input placeholder="车险承保公司" maxLength="25" v-decorator="['insuranceCarriers', { rules: [{ required: true, message: '车险承保公司不能为空' }, { pattern: /^[\s\S]{1,25}$/, message: '请输入正确的车险承保公司'}] }]"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" >
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="车辆损失险保单号">
            <a-input placeholder="车辆损失险保单号" maxLength="25" v-decorator="['lossPolicy', { rules: [{ required: true, message: '车辆损失险保单号不能为空' }, { pattern: /^[\da-zA-Z]{1,25}$/, message: '请输入正确的车辆损失险保单号'}] }]"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" >
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="保额">
            <a-input placeholder="保额" maxLength="10" v-decorator="['insuredAmount', { rules: [{ required: true, message: '保额不能为空' }, , { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的保额'}] }]"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" >
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="商业险起保日期">
            <!-- <a-input placeholder="商业险起保日期" v-decorator="['insuranceStartdate']"/> -->
            <a-date-picker valueFormat="YYYY-MM-DD" v-decorator="['insuranceStartdate', { rules: [{ required: true, message: '商业险起保日期不能为空' }] }]" style="width: 100%" placeholder="商业险起保日期"/>
          </a-form-item>
        </a-col>
        <a-col :md="24" >
          <div class="title">
            <div class="titleRece"></div>
            <span class="titleText">项目承保信息</span>
          </div>
        </a-col>
        <a-col :md="12" >
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="投保方案">
            <a-select @change="handleinsuranceScheme" v-decorator="['insuranceScheme', {initialValue:'', rules: [{ required: true }] }]">
              <a-select-option v-for="e in schemeConfigList" :key="e" :value="e.schemeName">{{ e.schemeName }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="12" >
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="保险费">
            <a-input placeholder="保险费" disabled v-decorator="['insurancePremium', {rules: [{ required: true }]} ]"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" >
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="赔偿限额">
            <a-input placeholder="赔偿限额" v-decorator="['compensationLimit', {rules: [{ required: true }]}]"/>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>
<script>
import moment from 'moment'
import GenerateProtocol from '../components/generateProtocol'
import GenerateServiceDeclaration from '../components/generateServiceDeclaration'
import { saveSysBusinessInfo,
  delSysBusinessInfo,
  insertOrderId,
  updateStatus,
  updateAgreement,
  getSysDcarbrandClassifyConfigList,
  getSysInsuranceSchemeConfigList,
  getSchemeName
} from '@/api/system'
import pick from 'lodash.pick'
export default {
  name: 'SysBusinessInfoModal',
  props: {
  },
  components: {
    GenerateProtocol,
    GenerateServiceDeclaration
  },
  data () {
    return {
      visible: false,
      title: '新建订单',
      labelCol: {
        xs: { span: 10 },
        sm: { span: 10 }
      },
      wrapperCol: {
        xs: { span: 14 },
        sm: { span: 14 }
      },
      confirmLoading: false,
      mdl: {},
      form: this.$form.createForm(this),
      datePicker: '',
      serviceAgreement: true,
      serviceStatement: true,
      clickOrder: true,
      orderIdObj: [],
      id: null,
      brandClassList: [],
      orderInfoObj: {},
      paramsCarBrand: '',
      schemeConfigList: [],
      schemeName: ''
    }
  },
  beforeCreate () {
  },
  mounted () {
    this.getbrandClassifyConfigList()
    this.loadSysInsuranceSchemeConfigList()
  },
  computed: {
    formData () {
      return {
        dealerName: this.orderIdObj.dealerName || '',
        startTime: moment().format('YYYY年MM月DD日'),
        endTime: moment().add(1, 'year').subtract(1, 'day').format('YYYY年MM月DD日'),
        ...this.orderInfoObj
      }
    }
  },
  methods: {
    async getbrandClassifyConfigList () {
      const res = await getSysDcarbrandClassifyConfigList()
      if (res.code === 0) {
        this.brandClassList = res.rows
      }
    },
    async add () {
      this.serviceAgreement = true
      this.serviceStatement = true
      this.clickOrder = true
      const res = await insertOrderId()
      this.orderIdObj = {
        orderId: res.rows[0].orderId,
        serviceContractNo: res.rows[0].serviceContractNo,
        id: res.rows[0].id,
        userId: res.rows[0].userId,
        orderTime: res.rows[0].orderTime,
        dealerName: res.rows[0].dealerName,
        organCode: res.rows[0].organCode
      }
      this.id = res.rows[0].id
      this.title = '新建订单'
      this.visible = true
      this.form.resetFields()
      this.$nextTick(() => {
        this.form.setFieldsValue(this.orderIdObj)
      })
    },
    edit (record) {
      this.serviceAgreement = true
      this.serviceStatement = true
      this.clickOrder = true
      this.schemeName = ''
      this.title = '编辑'
      this.mdl = Object.assign(this.orderIdObj, record)
      this.id = record.id
      this.visible = true
      this.handlerCarBrand(record.carBrand)
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.mdl, 'compensationLimit', 'insurancePremium', 'insuranceScheme', 'insuranceStartdate', 'insuredAmount', 'lossPolicy', 'insuranceCarriers', 'engineNo', 'vinNo', 'carNumber', 'iphone', 'serviceStakeholders', 'idCard', 'carName', 'brandModel', 'carBrand', 'saleName', 'carType', 'serviceContractNo', 'orderTime', 'orderId', 'id', 'carTypeName'))
      })
    },
    cancel () {
      if (this.title === '编辑') return
      this.form.validateFields((err, values) => {
        console.log(!err)
        const newTime = moment(values.orderTime)
        const lastTime = moment().add(1, 'year').format('YYYY-MM-DD')
        if (!moment(values.orderTime).isSame(values.insuranceStartdate)) {
          const flagLeft = moment(newTime).isBefore(values.insuranceStartdate)
          const flagRight = moment(values.insuranceStartdate).isBefore(lastTime)
          let rightSide = true
          if (moment(lastTime).isSame(values.insuranceStartdate)) {
            rightSide = true
          } else {
            rightSide = moment(lastTime).isBefore(values.insuranceStartdate)
          }
          const isFlagRequest = flagLeft && flagRight
          if (rightSide) {
            return this.$message.error('商业保险已脱保，不符合投保条件')
          }
          console.log(isFlagRequest, flagLeft, flagRight)
          if (isFlagRequest || !flagLeft) {
            this.$message.error('请准备验车照片')
          }
        }
        this.confirmLoading = true
        saveSysBusinessInfo({ ...values, id: this.orderIdObj.id }).then(res => {
          if (res.code === 0) {
            this.orderInfoObj = values
            this.$message.success('保存成功')
            this.$emit('ok')
            this.visible = false
            this.mdl = {}
          } else {
            this.$message.error(res.msg)
          }
        }).catch(() => {
          this.$message.error('系统错误，请稍后再试')
        }).finally(() => {
          this.confirmLoading = false
        })
      })
    },
    handleSubmit (e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          const newTime = moment(values.orderTime)
          const lastTime = moment(values.orderTime).add(1, 'year').format('YYYY-MM-DD')
          if (!moment(values.orderTime).isSame(values.insuranceStartdate)) {
            const flagLeft = moment(newTime).isBefore(values.insuranceStartdate)
            const flagRight = moment(values.insuranceStartdate).isBefore(lastTime)
            let rightSide = true
            if (moment(lastTime).isSame(values.insuranceStartdate)) {
              rightSide = true
            } else {
              rightSide = moment(lastTime).isBefore(values.insuranceStartdate)
            }
            const isFlagRequest = flagLeft && flagRight
            if (rightSide || !flagLeft) {
              return this.$message.error('商业保险已脱保，不符合投保条件')
            }
            console.log(isFlagRequest, flagLeft, flagRight)
            if (isFlagRequest) {
              this.$message.error('请准备验车照片')
            }
          }
          this.confirmLoading = true
          saveSysBusinessInfo({ ...values, id: this.id }).then(res => {
            if (res.code === 0) {
              this.orderInfoObj = values
              this.$message.success('保存成功')
              this.$emit('ok')
              this.serviceAgreement = false
            } else {
              this.$message.error(res.msg)
            }
          }).catch(() => {
            this.$message.error('系统错误，请稍后再试')
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    },
    delByIds () {
      delSysBusinessInfo({ ids: this.mdl.id }).then(res => {
        if (res.code === 0) {
          this.$message.success('删除成功')
          this.$emit('ok')
          this.visible = false
        } else {
          this.$message.error(res.msg)
        }
        this.selectedRowKeys = []
      })
    },
    async handleServiceAgreement () {
      const res = await updateAgreement({
        id: this.orderIdObj.id
      })
      console.log(res)
      this.serviceStatement = false
    },
    handleServiceStatement () {
      this.clickOrder = false
    },
    async orderCompletion () {
      const params = {
        id: this.mdl.id
      }
      if (this.title === '新建订单') {
        params.id = this.orderIdObj.id
      }
      const res = await updateStatus(params)
      if (res.code === 0) {
        this.$emit('ok')
      }
      this.visible = false
      this.mdl = {}
    },
    handlerCarBrand (val) {
      const brandClassList = this.brandClassList.filter((e) => e.carBrand === val)
      if (brandClassList.length) {
        if (brandClassList[0].brandClassify === '高端') {
          this.paramsCarBrand = 'highInsurancePremium'
        } else if (brandClassList[0].brandClassify === '中端') {
          this.paramsCarBrand = 'middleInsurancePremium'
        } else if (brandClassList[0].brandClassify === '低端') {
          this.paramsCarBrand = 'lowInsurancePremium'
        }
      }
      if (this.schemeName) {
        this.loadSchemeName()
      }
    },
    handleinsuranceScheme (val) {
      this.schemeName = val
      if (this.paramsCarBrand) {
        this.loadSchemeName()
      }
    },
    async loadSchemeName () {
      console.log(this.schemeName, '----')
      const res = await getSchemeName(this.schemeName)
      const compensationLimit = (res[this.paramsCarBrand] * 1 * 0.15).toFixed(2)
      this.form.setFieldsValue({
        insurancePremium: (res[this.paramsCarBrand]).toFixed(2),
        compensationLimit
      })
    },
    async loadSysInsuranceSchemeConfigList () {
      const res = await getSysInsuranceSchemeConfigList()
      if (res.code === 0) {
        this.schemeConfigList = res.rows
      }
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-form-item-control{
    max-width: 180px;
    min-width: 140px;
  }
.headCard{
  height: 60px;
  padding: 12px;
  background: #BAE7FF;
  border: 1px solid #7dc4ea;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  flex-direction: column;
  margin-bottom: 23px;
}
.title{
  display: flex;
  .titleRece{
    width: 2px;
    height: 16px;
    background: #227FE6;
    margin-right: 8px;
  }
  .titleText{
    font-family: "PingFangSC-Semibold";
    font-size: 14px;
    color: #333333;
    letter-spacing: 0;
    line-height: 18px;
    font-weight: 600;
  }
}
.footerBox{
  display: flex;
  justify-content: space-around;
  padding: 0 30px 30px 30px;
}
/deep/ .ant-modal-footer{
  border: none;
}
.button{
  width: 120px;
  height: 26px;
  border-radius: 4px;
}
/deep/ .ant-btn-primary-disabled, .ant-btn-primary.disabled, .ant-btn-primary[disabled], .ant-btn-primary-disabled:hover, .ant-btn-primary.disabled:hover, .ant-btn-primary[disabled]:hover, .ant-btn-primary-disabled:focus, .ant-btn-primary.disabled:focus, .ant-btn-primary[disabled]:focus, .ant-btn-primary-disabled:active, .ant-btn-primary.disabled:active, .ant-btn-primary[disabled]:active, .ant-btn-primary-disabled.active, .ant-btn-primary.disabled.active, .ant-btn-primary[disabled].active{
    color: #999999;
    background-color: #EAEAEA;
    border: none;
    text-shadow: none;
    -webkit-box-shadow: none;
    box-shadow: none;
}
</style>
